Online-Academy
Look, Read, Understand, Apply

File Handling

File Handling in Python

File handling allows to store data permanently, later retrieve it. This is usually used for saving records, logs, configurations, or user data.

Opening a File

Python uses the open() function to work with files.

file = open("filename","mode")

File Modes
  • r : Read
  • w : Write(creates new file or overwrites existing)
  • a : Append (adds data at the end)
  • x : Create (error if file exists)
  • rb / wb : Read/Write in binary mode

Writing to a File

    file = open("records.txt","w")
    file.write("Hello, this is Python file handling.\n")
    file.write("Writing to a file.")
    file.close()
Using with
    with open("records_i.txt","w") as file:
        file.write("File will be close automatically!")
        file.write("No need to call close method.")
Reading from a file
    with open("records_i.txt","r") as file:
        content = file.read()
        print(content)

Reading Line by Line
    with open("records_i.txt","r") as file:
        for l in file:
            print(l.strip())
Reading one Line
    file = open("records_i.txt","r")
    print("Line:: ".file.readline())
    file.close()
Appending to a File
    with open("records_i.txt","a") as file:
        file.write("\nThis line will be added to file, old content will not be erased.")
Examples to work with custom function

def writeToFile():
    file = open("data.txt", "a")
    file.write("Writing to file using python code")
    file.close()

def readFromFile():
    file = open("data.txt", "r")
    data = file.read()
    print(data)

def writeToFile2():
    with open("data_2.txt", "w") as file:
        file.write("Writing to file using python code")
        file.write("\nHello this will appear in next line")
        file.write("\nThis will appear in third line")
        file.close()

def readFromFile2():
    with open("data_2.txt","r") as file:
        for line in file.read():
            print(line,end="")
    with open("test.txt", 'r') as f:
        print(f.mode())
        f_contents = f.readline()
        print(f_contents,end="")

        for line in f:
            print(line,end="")
        size_to_read = 10
        print(f.tell())

        f.seek(0) #begining

        while len(f_contents) > 0:
            print(f_contents,end="")

        f_contents = f.read(size_to_read)

        with open("test.txt", 'w') as f:
            f.write("Hello")
            f.seek(0)
            f.write("World")
        with open("test.jpg", 'w') as f:
            with open("test_copy.jpg","w") as wf:
                for line in f:
                    wf.write(line)
Example: random access
    with open("test.txt", 'r') as f:
        print("File is opened in Mode: ",f.mode)
        f_contents = f.readline()
        print(f_contents,end="")

        for line in f:
            print(line,end="")

        print("\nCursor Position: ",f.tell())
        f.seek(0) #begining

        print("\nCursor Position: ", f.tell())
        #while len(f_contents) > 0:
        #    print(f_contents,end="")

        size_to_read = 10 #size of data to read
        f_contents = f.read(size_to_read) #reading only first 10 bytes
        print("\nFile Contents: ",f_contents)
    with open("test.text", 'w') as f:
        f.write("Hello")  #writing Hello to fine
        f.seek(0)         # bringing cursor to 0 th position
        f.write("World")  # write World at 0 th position

    with open("test.jpg", 'r') as f:
        with open("test_copy.jpg","w") as wf:
            for line in f:
                wf.write(line)